package org.wedding.center.pay.wxpay.config;

import java.io.*;
import java.nio.file.Files;

/**
 * 从jar包中提取资源到指定目录
 * 用于获取微信支付认证文件
 */
public class JarResourceExtractor {
    // 从jar包中提取资源到指定目录
    public static File extractResource(String resourcePath, String targetDir) throws IOException {
        // 获取资源的输入流
        InputStream inputStream = JarResourceExtractor.class.getClassLoader().getResourceAsStream(resourcePath);
        // 如果资源不存在，抛出异常
        if (inputStream == null) {
            throw new FileNotFoundException("Resource not found: " + resourcePath);
        }

        // 创建目标文件
        File targetFile = new File(targetDir, new File(resourcePath).getName());
        // 将资源写入目标文件
        try (OutputStream outputStream = new FileOutputStream(targetFile)) {
            byte[] buffer = new byte[1024];
            int length;
            // 读取资源并写入目标文件
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
        }
        // 返回目标文件
        return targetFile;
    }

    // 获取指定路径下的apiclient_key.pem文件
    public static File getPemFile(String resourcePath, String targetDir) throws FileNotFoundException {
        String filePath = targetDir +resourcePath;
        File pemFile = new File(filePath);
        if (!pemFile.exists()) {
            throw new FileNotFoundException("File not found: " + filePath);
        }
        return pemFile;
    }
}
